package com.cancan.cloud.shop.utils;

import com.alibaba.fastjson.JSON;
import com.cancan.cloud.shop.enums.GatewayEnum;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhouFufeng
 * @since 2020/3/13
 **/
public class BuilderHeader {

    /**
     * 添加请求头
     * @param exchange
     * @param headerName
     * @param object
     * @return
     */
    public static ServerHttpRequest addHeader(ServerWebExchange exchange,String headerName,Object object) {
        return exchange.getRequest().mutate().header(headerName, JSON.toJSONString(object)).build();
    }


    /**
     * 添加错误请求头
     * @param exchange
     * @param headerName 请求头名
     * @param gatewayEnum  错误枚举信息
     * @return 已添加Header的请求
     */
    public static ServerHttpRequest addHeader(ServerWebExchange exchange,String headerName, GatewayEnum gatewayEnum) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("code", gatewayEnum.getCode());
        map.put("message", gatewayEnum.getMessage());
        return exchange.getRequest().mutate().header(headerName, JSON.toJSONString(map)).build();
    }


    /**
     * 解析clientId
     * @param header
     * @return
     */
    public static Long parseClientId(String header) {
        Assert.notNull(header, "Authentication header must not be null.");
        String[] strings = parseAuthHeader(header);
        return strings.length > 0 && StringUtils.isNumeric(strings[0]) ? Long.parseLong(strings[0]) : null;
    }

    /**
     * 解析header 中的token
     * @param header
     * @return
     */
    public static String[] parseAuthHeader(String header) {
        if (header != null && header.length() != 0) {
            String[] arr = header.split("\\s+");
            return arr.length != 2
                    || !AuthScheme.BEARER.equalsIgnoreCase(arr[0])
                    && !AuthScheme.BASIC.equalsIgnoreCase(arr[0])
                    && !AuthScheme.DEVICE.equalsIgnoreCase(arr[0])
                    ? AuthHeadHelper.EMPTY_STRING_ARRAY : AuthHeadHelper.decodeAuth(arr[1]);
        } else {
            return AuthHeadHelper.EMPTY_STRING_ARRAY;
        }
    }

}
